﻿namespace Leetcode.N0380;

public class RandomizedSet
{
    private readonly IList<int> list;
    private readonly IDictionary<int, int> dic;
    private readonly System.Random random;
    public RandomizedSet()
    {
        this.dic = new Dictionary<int, int>();
        this.list = new List<int>();
        this.random = new Random();
    }

    public bool Insert(int val)
    {
        if (this.dic.ContainsKey(val))
        {
            return false;
        }
        this.dic.Add(val, this.list.Count);
        this.list.Add(val);
        return true;
    }

    public bool Remove(int val)
    {
        if (!this.dic.ContainsKey(val))
        {
            return false;
        }

        var last = this.list[this.list.Count - 1];
        var index = this.dic[val];
        this.list[index] = last;
        this.dic[last] = index;
        this.dic.Remove(val);
        this.list.RemoveAt(this.list.Count - 1);
        return true;
    }

    public int GetRandom()
    {
        var i = this.random.Next(0, this.list.Count);
        return this.list[i];
    }
}
